﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using IFDB.Models.Contexts;
using IFDB.Models.Foundation;
using IFDB.ResourceLibrary;

namespace IFDB.Models.Tables
{
    public class LookupPerson : BaseTable<LookupPerson>
    {
        [Key]
        public Guid LookupPersonId { get; set; }
        public Site Site { get; set; }

        [StringLength(25)]
        public string LookupId { get; set; }
        public Guid PersonId { get; set; }

        [ForeignKey("PersonId")]
        public virtual Person Person { get; set; }

        public static LookupPerson CreateNew(Site site, string lookupId, Guid personId)
        {
            return new LookupPerson()
            {
                LookupPersonId = Guid.NewGuid(),
                Site = site,
                LookupId = lookupId,
                PersonId = personId
            };
        }

        public static LookupPerson Update(LookupPerson lookupPerson, Site site, string lookupId, Guid personId)
        {
            lookupPerson.Site = site;
            lookupPerson.LookupId = lookupId;
            lookupPerson.PersonId = personId;

            return lookupPerson;
        }

        public static LookupPerson Search(IFDBContext db, Site site, string lookupId)
        {
            var localQuery = from lookupPerson in db.LookupPersons.Local
                             where lookupPerson.Site == site
                             && lookupPerson.LookupId == lookupId
                             select lookupPerson;

            var query = from lookupPerson in db.LookupPersons
                        where lookupPerson.Site == site
                        && lookupPerson.LookupId == lookupId
                        select lookupPerson;

            var search = ProcessSearch(localQuery, query, false);
            return search != null ? search.Single() : null;
        }
    }
}
